package com.sx.pipeline.ui.web

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.net.Uri
import android.net.http.SslError
import android.os.*
import android.provider.MediaStore
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.webkit.*
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Route
import com.permissionx.guolindev.PermissionX
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.app.base.CYDataBindingBaseActivity
import com.sx.pipeline.app.model.CYBaseViewModel
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.databinding.ActWebBinding
import java.io.File
import java.lang.String.format
import android.text.format.DateFormat
import android.view.KeyEvent
import androidx.annotation.RequiresApi
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ToastUtils
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.sx.pipeline.utils.CompressHelper
import com.sx.pipeline.utils.GlideEngine
import com.sx.pipeline.utils.MyWebViewClients
import com.sx.pipeline.utils.PermissionHelper
import java.util.*
import java.util.Calendar.*


/**
 * @Author: YY
 * @Date: 2022/4/5
 * @Description: 联系客服
 */
@Route(path = RoutePath.Setting.CONTACT_SERVICE)
class WebViewActivity : CYDataBindingBaseActivity<ActWebBinding, CYBaseViewModel>(R.layout.act_web),
    View.OnClickListener {
    private var webUrl =
        "https://web.jiaxincloud.com/onekey.html?id=yzbtyxnuyjvsdg&appName=gxt365&appChannel=20001"
    private var mUploadCallbackAboveL: ValueCallback<Array<Uri>>? = null
    private var mUploadCallbackBelow: ValueCallback<Uri>? = null
    private var imageUri: Uri? = null
    private val REQUEST_CODE = 1234

//    private val handler: Handler = object : Handler() {
//        override fun handleMessage(message: Message) {
//            when (message.what) {
//                1 -> {
//                    webViewGoBack()
//                }
//            }
//        }
//    }

    override fun initData() {
        mBinding.setVariable(BR.onClick, this)
        mBinding.titleBar.leftView.setOnClickListener {
            finish()
        }
        initWebView()
    }


    private fun webViewGoBack() {
        mBinding.webview?.goBack()
    }

    override fun initViewObservable() {
        super.initViewObservable()
    }

    override fun onClick(v: View?) {
    }

    //初始化webView
    private fun initWebView() {
        //从布局文件中扩展webView
        initWebViewSetting()
    }

    //初始化webViewSetting
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private fun initWebViewSetting() {
        val settings = mBinding.webview.settings
        settings.useWideViewPort = true
        settings.loadWithOverviewMode = true
        settings.domStorageEnabled = true
        settings.defaultTextEncodingName = "UTF-8"
        settings.allowContentAccess = true // 是否可访问Content Provider的资源，默认值 true
        settings.allowFileAccess = true // 是否可访问本地文件，默认值 true
        // 是否允许通过file url加载的Javascript读取本地文件，默认值 false
        settings.allowFileAccessFromFileURLs = false
        // 是否允许通过file url加载的Javascript读取全部资源(包括文件,http,https)，默认值 false
        settings.allowUniversalAccessFromFileURLs = false
        //开启JavaScript支持
        settings.javaScriptEnabled = true
        // 支持缩放
        settings.setSupportZoom(true)
        //辅助WebView设置处理关于页面跳转，页面请求等操作
        mBinding.webview.webViewClient = MyWebViewClients()
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            mBinding.webview.getSettings()
                .setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

        }
        mBinding.webview.getSettings().setBlockNetworkImage(false);
//        mBinding.webview.setOnKeyListener(object : View.OnKeyListener {
//            override fun onKey(v: View?, keyCode: Int, event: KeyEvent?): Boolean {
//                if ((keyCode == KeyEvent.KEYCODE_BACK) && mBinding.webview.canGoBack()) {
//                    handler.sendEmptyMessage(1);
//                    return true;
//                }
//                return false;
//            }
//
//        });
        //辅助WebView处理图片上传操作
        mBinding.webview.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                //                if (newProgress == 100) {
                //                    progressBar.setVisibility(View.GONE);//加载完网页进度条消失
                //                } else {
                //                    progressBar.setProgress(newProgress);//设置进度值
                //                    progressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                //                }
            }

            /**
             * 8(Android 2.2) <= API <= 10(Android 2.3)回调此方法
             */
            private fun openFileChooser(uploadMsg: ValueCallback<Uri>) {
                Log.e("WangJ", "运行方法 openFileChooser-1")
                // (2)该方法回调时说明版本API < 21，此时将结果赋值给 mUploadCallbackBelow，使之 != null
                mUploadCallbackBelow = uploadMsg
                takePhoto()
            }

            /**
             * 11(Android 3.0) <= API <= 15(Android 4.0.3)回调此方法
             */
            fun openFileChooser(uploadMsg: ValueCallback<Uri>, acceptType: String) {
                Log.e("WangJ", "运行方法 openFileChooser-2 (acceptType: $acceptType)")
                // 这里我们就不区分input的参数了，直接用拍照
                openFileChooser(uploadMsg)
            }

            /**
             * 16(Android 4.1.2) <= API <= 20(Android 4.4W.2)回调此方法
             */
            fun openFileChooser(
                uploadMsg: ValueCallback<Uri>,
                acceptType: String,
                capture: String
            ) {
                Log.e(
                    "WangJ",
                    "运行方法 openFileChooser-3 (acceptType: $acceptType; capture: $capture)"
                )
                // 这里我们就不区分input的参数了，直接用拍照
                openFileChooser(uploadMsg)
            }

            /**
             * API >= 21(Android 5.0.1)回调此方法
             */
            override fun onShowFileChooser(
                webView: WebView,
                valueCallback: ValueCallback<Array<Uri>>,
                fileChooserParams: FileChooserParams
            ): Boolean {
                Log.e("WangJ", "运行方法 onShowFileChooser")
                // (1)该方法回调时说明版本API >= 21，此时将结果赋值给 mUploadCallbackAboveL，使之 != null
                mUploadCallbackAboveL = valueCallback
                takePhoto()
                return true
            }
        }
        //加载地址
        mBinding.webview.loadUrl(webUrl)
    }


    /**
     * 调用相机
     */
    private fun takePhoto() {
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
            Toast.makeText(this@WebViewActivity, "设备无摄像头", Toast.LENGTH_SHORT).show();
            return;
        }
        PermissionHelper.requestTip(this,"上次图片需要授权相机和读写权限",object :
            PermissionUtils.SimpleCallback{
            override fun onGranted() {
                // 指定拍照存储位置的方式调起相机
                val filePath = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
                    .toString() + File.separator;
                val fileName = "IMG_" + DateFormat.format(
                    "yyyyMMdd_hhmmss",
                    getInstance(Locale.CHINA)
                ) + ".jpg"
                imageUri = Uri.fromFile(File(filePath + fileName))

                val captureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
                val Photo = Intent(
                    Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                )
                val chooserIntent = Intent.createChooser(Photo, "Image Chooser")
                chooserIntent.putExtra(
                    Intent.EXTRA_INITIAL_INTENTS,
                    arrayOf<Parcelable>(captureIntent)
                )
                startActivityForResult(chooserIntent, REQUEST_CODE)
            }

            override fun onDenied() {
                ToastUtils.showShort("请授权后再继续操作")
            }
        },Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA)

//        PermissionX.init(this)
//            .permissions(
//                Manifest.permission.READ_EXTERNAL_STORAGE,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                Manifest.permission.CAMERA
//            )
//            .onExplainRequestReason { scope, deniedList ->
//                scope.showRequestReasonDialog(
//                    deniedList,
//                    "核心基础功能基于这些权限,请允许,否则影响app正常使用",
//                    "确认",
//                    "取消"
//                )
//            }
//            .onForwardToSettings { scope, deniedList ->
//                scope.showForwardToSettingsDialog(
//                    deniedList,
//                    "您需要手动在“设置”中允许必要的权限",
//                    "确定",
//                    "取消"
//                )
//            }
//            .request { allGranted, grantedList, deniedList ->
//                if (allGranted) {
//                    // 指定拍照存储位置的方式调起相机
//                    val filePath = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
//                        .toString() + File.separator;
//                    val fileName = "IMG_" + DateFormat.format(
//                        "yyyyMMdd_hhmmss",
//                        getInstance(Locale.CHINA)
//                    ) + ".jpg"
//                    imageUri = Uri.fromFile(File(filePath + fileName))
//
//                    val captureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
//                    captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
//                    val Photo = Intent(
//                        Intent.ACTION_PICK,
//                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI
//                    )
//                    val chooserIntent = Intent.createChooser(Photo, "Image Chooser")
//                    chooserIntent.putExtra(
//                        Intent.EXTRA_INITIAL_INTENTS,
//                        arrayOf<Parcelable>(captureIntent)
//                    )
//                    startActivityForResult(chooserIntent, REQUEST_CODE)
//                } else {
//                    ToastUtils.showShort(getString(R.string.txt_these_permissions_are_denied))
//                }
//            }


    }

    /**
     * Android API < 21(Android 5.0)版本的回调处理
     * @param resultCode 选取文件或拍照的返回码
     * @param data 选取文件或拍照的返回结果
     */
    private fun chooseBelow(resultCode: Int, data: Intent?) {
        Log.e("WangJ", "返回调用方法--chooseBelow")
        if (Activity.RESULT_OK == resultCode) {
            updatePhotos()
            if (data != null) {
                // 这里是针对文件路径处理
                val uri = data.data
                if (uri != null) {
                    Log.e("WangJ", "系统返回URI：$uri")
                    mUploadCallbackBelow!!.onReceiveValue(uri)
                } else {
                    mUploadCallbackBelow!!.onReceiveValue(null)
                }
            } else {
                // 以指定图像存储路径的方式调起相机，成功后返回data为空
                Log.e("WangJ", "自定义结果：" + imageUri.toString())
                mUploadCallbackBelow!!.onReceiveValue(imageUri)
            }
        } else {
            mUploadCallbackBelow!!.onReceiveValue(null)
        }
        mUploadCallbackBelow = null
    }

    /**
     * Android API >= 21(Android 5.0) 版本的回调处理
     * @param resultCode 选取文件或拍照的返回码
     * @param data 选取文件或拍照的返回结果
     */
    private fun chooseAbove(resultCode: Int, data: Intent?) {
        Log.e("WangJ", "返回调用方法--chooseAbove")
        if (Activity.RESULT_OK == resultCode) {
            updatePhotos()
            if (data != null) {
                // 这里是针对从文件中选图片的处理
                val results: Array<Uri>
                val uriData = data.data
                if (uriData != null) {
                    results = arrayOf(uriData)
                    for (uri in results) {
                        Log.e("WangJ", "系统返回URI：$uri")
                    }
                    mUploadCallbackAboveL!!.onReceiveValue(results)
                } else {
                    mUploadCallbackAboveL!!.onReceiveValue(null)
                }
            } else {
                Log.e("WangJ", "自定义结果：" + imageUri.toString())
                mUploadCallbackAboveL!!.onReceiveValue(arrayOf(imageUri!!))
            }
        } else {
            mUploadCallbackAboveL!!.onReceiveValue(null)
        }
        mUploadCallbackAboveL = null
    }

    private fun updatePhotos() {
        // 该广播即使多发（即选取照片成功时也发送）也没有关系，只是唤醒系统刷新媒体文件
        val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
        intent.data = imageUri
        sendBroadcast(intent)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE) {
            // 经过上边(1)、(2)两个赋值操作，此处即可根据其值是否为空来决定采用哪种处理方法
            if (mUploadCallbackBelow != null) {
                chooseBelow(resultCode, data)
            } else if (mUploadCallbackAboveL != null) {
                chooseAbove(resultCode, data)
            } else {
                Toast.makeText(this, "发生错误", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        if (mBinding.webview.canGoBack()){
            mBinding.webview.goBack()
        }else{
            finish()
        }
    }
}